<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/20
 * Time: 23:07
 */
namespace app\share\model;

class Ping
{
    /**
     * ping域名或者ip接口
     *@param  address   string    ip或者域名
     *@return  array
     */
    public function pingAddress($address)
    {
        $ping_cmd = "ping -c 1 -w 5 " . $address;
        exec($ping_cmd, $info);
        if($info == null)
        {
            return ['code'=>404,'msg'=>"Ping请求找不到主机".$address.",请检查该名称,然后重试"];
        }
        //判断是否丢包
        $str1 = $info['4'];
        $str2 = "1 packets transmitted, 1 received, 0% packet loss";
        if($str1 === "")
        {
            return ['code'=>402,'msg'=>"请求超时,当前请求地址为私网或者禁Ping"];
        }
        if( strpos( $str1 , $str2 ) === false)
        {
            return ['code'=>403,'msg'=>"当前网络堵塞,请求无法成功,请稍后重试"];
        }
        $ping_time_line = end($info);
        $ping_time = explode("=", $ping_time_line)[1];
        $ping_time_min = explode("/", $ping_time)[0] / 1000.0;
        $ping_time_avg = explode("/", $ping_time)[1] / 1000.0;
        $ping_time_max = explode("/", $ping_time)[2] / 1000.0;

        $result = array();
        $result['ping_address'] = $info['0'];
        $result['ping_min'] = $ping_time_min;
        $result['ping_avg'] = $ping_time_avg;
        $result['ping_max'] = $ping_time_max;
        return ['code'=>200,'msg'=>"请求成功",'data'=>$result];
    }
}